import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable';
import { map, catchError } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';
import { throwError } from 'rxjs/internal/observable/throwError';

const RESPONSE_STATE = {
  0: '服务器发生错误，请检查服务器',
  1: '服务器成功返回请求数据',
  2: '表单提交存在不合适的数据',
  5: 'LDAP 初始化',
  10: '用户没有权限（令牌、用户名、密码错误)',
  20: '用户得到授权，但是访问是被禁止的',
  30: '许可校验异常',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作',
  401: '用户没有权限（令牌、用户名、密码错误)',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作',
  500: '服务器发生错误，请检查服务器',
  502: '网关错误',
  503: '服务不可用，服务器暂时过载或维护',
  504: '网关超时'
};

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
  constructor(private injector: Injector) { }

  get msg(): NzMessageService {
    return this.injector.get(NzMessageService);
  }

  private goTo(url: string) {
    setTimeout(() => this.injector.get(Router).navigateByUrl(url));
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse && event.status === 200) {
          if (event.body.status === 0 || event.body.status >= 10) {
            console.log('event1====》', event);
            throw event;
          }
        }
        console.log('event2====》', event);
        return event;
      }),
      catchError((err: any) => {
        console.log('出错');
        return this.handleExceptionRespData(err);
      })
    );
  }

  private handleExceptionRespData(err: any) {
    let errortext = null;
    let errstatus;
    if (err instanceof HttpErrorResponse) {
      errstatus = err.status;
      errortext = RESPONSE_STATE[errstatus] || `请求错误 ${errstatus}: ${err.message}`;
    } else if (err instanceof HttpResponse) {
      errstatus = err.body.status;
      errortext = RESPONSE_STATE[errstatus];
    }
    switch (errstatus) {
      case 10:
      case 401:
        this.goTo('/login');
        break;
      case 20:
      case 403:
        this.goTo('/403');
        break;
      case 30:
        this.goTo('/passport/license');
        break;
      default:
        this.msg.error(errortext);
        break;
    }
    return throwError(errortext);
  }
}
